package com.gitee.xmhzzz.component.mqtt.client.listener;


import com.alibaba.fastjson2.JSONObject;
import com.gitee.xmhzzz.component.mqtt.client.IMqttClient;
import com.gitee.xmhzzz.component.mqtt.client.MqttClientApp;
import com.gitee.xmhzzz.component.mqtt.client.config.MqttConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.cloud.endpoint.event.RefreshEventListener;
import org.springframework.context.ApplicationEvent;

import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;


@Slf4j
public class MqttConfigRefreshListener extends RefreshEventListener {

    private final MqttConfig config;

    private final IMqttClient mqttClient;
    private final ExecutorService mqttExecutorService;

    public MqttConfigRefreshListener(ContextRefresher refresh,
                                     MqttConfig config,
                                     IMqttClient mqttClient,
                                     ExecutorService mqttExecutorService) {
        super(refresh);
        this.config = config;
        this.mqttClient = mqttClient;
        this.mqttExecutorService = mqttExecutorService;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        String json = JSONObject.toJSONString(config);
        super.onApplicationEvent(event);
        if (event instanceof RefreshEvent && !StringUtils.equals(json, JSONObject.toJSONString(config))) {
            restartMqttClient(config);
        }
    }

    private void restartMqttClient(MqttConfig config) {
        if (mqttClient.isConnect()) {
            log.debug("start mqtt client restart. config[{}]", JSONObject.toJSONString(config));
            mqttClient.disconnect();
            startMqttClient(config);
            log.info("MQTT client restart. config[{}]", JSONObject.toJSONString(config));
        } else {
            startMqttClient(config);
        }
    }

    private void startMqttClient(MqttConfig config) {
        mqttExecutorService.execute(() -> {
                    log.debug("mqtt client start. config[{}]", JSONObject.toJSONString(config));
            mqttClient.connect().sync();
                    log.info("mqtt client start end. config[{}]", JSONObject.toJSONString(config));
                }
        );
    }

    @PreDestroy
    public void destroy() {
        try {
            mqttExecutorService.shutdown();
            log.info("销毁线程池mqttExecutorService");
        } catch (Throwable e) {
            log.error("销毁线程池异常mqttExecutorService", e);
        }
    }


}
